package com.example.mychat.Utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

@Slf4j
public class CustomHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("拦截器被执行");
        String requestUri = request.getURI().toString();
        Map<String, String> queryParams = UriComponentsBuilder.fromUriString(requestUri)
                .build(true)
                .getQueryParams()
                .toSingleValueMap();
        String token=queryParams.get("token");

        // 在这里设置请求头
        response.getHeaders().add("Authorization", token);
        return true; // 继续握手
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 握手成功后的逻辑
    }
}
